<template>
    <div class="app-content">
        <el-card class="search-card" shadow="never">
            <!-- 搜索部分 -->
            <el-row :gutter="10" class="search-section">
                <el-col :span="7">
                    <el-form-item label="所属租户：">
                        <el-select v-model="searchData.tenantIdList" multiple filterable clearable placeholder="选择租户"
                            style="width: 240px">
                            <el-option v-for="tenant in allDeptInfo" :key="tenant" :label="tenant.tenantName"
                                :value="tenant.tenantId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="用户名称：">
                        <el-input v-model="searchData.username" placeholder="请输入用户名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="手机号码：">
                        <el-input v-model="searchData.phone" placeholder="请输入手机号码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="状态">
                        <el-select v-model="searchData.status" placeholder="请选择状态">
                            <el-option label="正常" value="1"></el-option>
                            <el-option label="停用" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row :gutter="10" class="search-section2">
                <el-col :span="9">
                    <el-form-item label="创建时间：">
                        <div class="block">
                            <el-date-picker v-model="searchData.createTimeList" type="daterange" unlink-panels
                                range-separator=">>" start-placeholder="开始日期" end-placeholder="结束日期"
                                :shortcuts="shortcuts" />
                        </div>

                    </el-form-item>

                </el-col>
                <el-col :span="5">
                    <el-button type="primary" class="action-button" @click="search" :icon="Search">搜索</el-button>
                    <el-button @click="reset" type="primary" class="action-button" :icon="Refresh">重置</el-button>
                </el-col>
            </el-row>
        </el-card>
        <el-card class="search-card" shadow="never" style="margin-top: 10px;">
            <!-- 操作按钮组 -->
            <div class="button-group">
                <el-button class="action-button" type="primary" :icon="Edit" @click="handleAdd">增加</el-button>

                <el-button class="action-button" type="primary" :icon="Upload" @click="handleImport">导入</el-button>
                <input type="file" ref="fileInput" @change="handleFileUpload" style="display: none"
                    accept=".xlsx,.xls,.csv" />
                <el-button class="action-button" type="primary" :icon="Download" @click="handleExport">导出</el-button>
                <el-button class="action-button" type="primary" :icon="Delete" :disabled="!hasSelected"
                    @click="handleBatchDelete" plain>
                    删除
                </el-button>
                <el-button class="action-button" type="primary" :disabled="!hasSelected" @click="handleBatchEnable"
                    plain>
                    启用
                </el-button>
                <el-button class="action-button" type="primary" :disabled="!hasSelected" @click="handleBatchDisable"
                    plain>
                    禁用
                </el-button>
            </div>


            <!-- 数据表格 -->
            <el-table ref="tableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <!-- 多选框列 -->
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="username" label="用户名" width="140" />
                <el-table-column prop="nickname" label="昵称" width="140" />
                <el-table-column prop="gender" label="性别" width="100">
                    <template #default="scope">
                        {{ getGenderText(scope.row.gender) }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                            style="--el-switch-on-color: #6067eb; --el-switch-off-color: #dcdfe6"
                            @change="handleStatusChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" width="180" />
                <el-table-column prop="email" label="邮箱" width="180" />
                <el-table-column prop="remark" label="备注" />
                <!-- 操作列 -->
                <el-table-column label="操作" width="210">
                    <template #default="scope">
                        <el-button class="table-button" text type="primary" :icon="EditPen"
                            @click="handleEdit(scope.$index, scope.row)">
                            编辑</el-button>
                        <el-button class="table-button" text type="danger" :icon="Delete"
                            @click="handleRowDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination class="pagination-fixed" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" :current-page="pagination.currentPage"
                    :page-sizes="[10, 15, 20, 25, 30]" :page-size="pagination.pageSize"
                    layout="total, sizes, prev, pager, next" :total="pagination.totalNum">

                </el-pagination>
            </div>
        </el-card>
        <!-- 对话框 -->
        <el-dialog v-model="dialogVisible" title="Tips" width="600" :before-close="handleClose" @open="onOpen"
            @close="onClose" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
            <el-segmented v-model="segmentValue" :options="menuoOptions" size="large" />

            <template #footer>
                <div class="dialog-footer">
                    <el-button class="action-button" type="info" @click="dialogVisible = false">取消</el-button>
                    <el-button class="action-button" type="primary" @click="update()">
                        确认
                    </el-button>
                </div>
            </template>

            <el-form ref="dialogForm" style="max-width: 600px; margin-left: 30px;" :model="userForm" :rules="rules"
                label-width="auto" class="el-form" status-icon>

                <div v-show="segmentValue === 'basic'">
                    <el-form-item label="所属租户" prop="tenantName" v-show="dialogType == false">
                        <el-input v-model="userForm.tenantName" style="width: 200px;" readonly />
                    </el-form-item>
                    <el-form-item label="用户名" prop="username" required v-if="dialogType == true">
                        <el-input v-model="userForm.username" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="用户名" prop="username" required v-if="dialogType == false">
                        <el-input v-model="userForm.username" style="width: 200px;" readonly/>
                    </el-form-item>
                    <el-form-item label="密码" prop="password" required v-show="dialogType == true">
                        <el-input v-model="userForm.password" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname" required>
                        <el-input v-model="userForm.nickname" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="userForm.gender" style="width: 200px;">
                            <el-radio value="0">女</el-radio>
                            <el-radio value="1">男</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="userForm.phone" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="userForm.remark" style="width: 200px;" />
                    </el-form-item>
                </div>
                <div v-show="segmentValue === 'tenant' && dialogType == true">
                    <el-form-item label="租户" prop="tenantId">
                        <el-card style="width: 350px;border-radius: 8px; margin-top: 10px;" shadow="hover">
                            <el-select v-model="userForm.tenantId" filterable clearable placeholder="选择租户"
                                style="width: 240px">
                                <el-option v-for="tenant in allDeptInfo" :key="tenant" :label="tenant.tenantName"
                                    :value="tenant.tenantId" />
                            </el-select>
                        </el-card>

                    </el-form-item>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed,reactive } from 'vue'
import type { User, UserDTO } from '../../type/User';
import type { PaginationData } from '../../type/PaginationData';
import { ElMessage, ElMessageBox,FormInstance, FormRules } from 'element-plus';
import { Delete, Edit, Search,  Upload, Download, Refresh, EditPen } from '@element-plus/icons-vue'
import { updataUserState, getUserInfo, exportUserInfo, importUserInfo, searchUserInfo, addUser, updateUser, deleteUser, deleteBatch } from '../../api/Tenant/userApi';
import { getAllTenantInfo, findById } from '../../api/Tenant/tenantApi';
import { Tenant } from '../../type/Tenant';
import { onMounted } from 'vue'; 
import { globalVariables, setGlobalVar } from '../../config/globalVariables'; 

// 表格数据
const tableData = ref<User[]>([]);
//查询数据
const searchData = ref({
    username: "",
    phone: "",
    status: "",
    createTimeList: [],
    tenantIdList: [] as string[]
});


//分页
const isSearch = ref(false); // 判断是否为搜索状态

const pagination = ref<PaginationData<User>>({
    currentPage: 1,
    pageSize: 10,
    totalNum: 10,
    isMore: 0,
    totalPage: 0,
    startIndex: 0,
    items: []
});
//当每页条数发生了变化，调用此函数
const handleSizeChange = async (val: number) => {
    pagination.value.pageSize = val;
    pagination.value.currentPage = 1; // 切换每页条数时重置为第一页
    if (isSearch.value) {
        await search();  // 如果是搜索状态，调用搜索
    } else {
        await getUserData();  // 否则调用常规获取数据
    }
};
//当前页码发生变化，调用此函数
const handleCurrentChange = async (val: number) => {
    pagination.value.currentPage = val;
    if (isSearch.value) {
        await search();  // 如果是搜索状态，调用搜索
    } else {
        await getUserData();  // 否则调用常规获取数据
    }
};

// ---------------------
// 获取用户数据
const getUserData = async () => {

    const res = await getUserInfo(pagination.value?.currentPage, pagination.value?.pageSize);
    console.log('获取到的数据:', res);
    const data = res;

    // 更新表格数据
    tableData.value = data.items;

    // 更新分页信息
    pagination.value.currentPage = data.currentPage;
    pagination.value.pageSize = data.pageSize;
    pagination.value.totalNum = data.totalNum;
    pagination.value.isMore = data.isMore;
    pagination.value.totalPage = data.totalPage;
    pagination.value.startIndex = data.startIndex;

}
getUserData();


const allDeptInfo = ref<Tenant[]>()

//获取租户数据
const getTenantData = async () => {
    const res = await getAllTenantInfo();
    allDeptInfo.value = res;
}


getTenantData();
// 获取性别的中文表示
const getGenderText = (gender: string): string => {
    switch (gender) {
        case "1":
            return '男';
        case "0":
            return '女';
        default:
            return '男';
    }
};
// 状态切换的处理函数
const handleStatusChange = async(row: User) => {
    await updataUserState(row.username!, row.status!);
    
    ElMessage({
        message: `已将 ${row.username} 的状态更改为 ${row.status == "1" ? '正常' : '禁用'}`,
        type: 'success',
    }); 
};
//日期选择器
const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]


//------------搜索----------------
const search = async () => {
    isSearch.value = true;
    const res = await searchUserInfo(pagination.value.currentPage, pagination.value.pageSize, searchData.value);

    // 更新表格数据
    tableData.value = res.items;

    // 更新分页信息
    pagination.value.currentPage = res.currentPage;
    pagination.value.pageSize = res.pageSize;
    pagination.value.totalNum = res.totalNum;
    pagination.value.isMore = res.isMore;
    pagination.value.totalPage = res.totalPage;
    pagination.value.startIndex = res.startIndex;
}
const reset = async () => {
    isSearch.value=false;
    searchData.value.username = "";
    searchData.value.phone = "";
    searchData.value.status = "";
    searchData.value.createTimeList = [];
    searchData.value.tenantIdList = [];
    await getUserData();
}

// 处理顶部按钮操作
const handleAdd = async () => {
    console.log('增加按钮点击')
    dialogTitle.value = '新增用户'
    dialogVisible.value = true
    // 重置表单
    userForm.value = {}
    // 重置验证规则，避免触发验证 需要用setTimeout包裹
    setTimeout(() => {
        dialogForm.value?.clearValidate()
    }, 100)
    dialogType.value = true

}

//----------导入部分--------
const fileInput = ref<HTMLInputElement | null>(null);

// 触发文件输入
function handleImport() {
    fileInput.value?.click();
}
const handleFileUpload = async (event: Event) => {
    console.log('导入按钮点击')
    // 在此添加导入操作的逻辑
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (file) {
        const formData = new FormData();
        formData.append('file', file);
        await importUserInfo(formData);
        ElMessage.success('导入成功');
        // 重新获取数据
        await getUserData();
    }
}

const handleExport = async () => {
    console.log('导出按钮点击')
    // 在此添加导出操作的逻辑
    await exportUserInfo();
}

//------------------
// 管理选中行
const tableRef = ref<InstanceType<typeof import('element-plus')['ElTable']> | null>(null);
const selectedRows = ref<User[]>([]);

// 监听选中行变化
const handleSelectionChange = (selection: User[]) => {
    selectedRows.value = selection;
};

// 计算是否有选中行
const hasSelected = computed(() => selectedRows.value.length > 0);

// 批量删除处理函数
const handleBatchDelete = async() => {
    if (selectedRows.value.length === 0) return;

    ElMessageBox.confirm(
        `确定删除选中的 ${selectedRows.value.length} 条数据吗?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async() => {
            tableData.value = tableData.value.filter(
                (row) => !selectedRows.value.includes(row)
            );
            console.log('selectedRows.value', selectedRows.value)
            const ids: string[] = selectedRows.value.map((row) => row.userId as string);  // 类型断言，确保返回的都是 string 类型
            await deleteBatch(ids)
            ElMessage.success('批量删除成功');
            selectedRows.value = [];
            await getUserData();
        })
        .catch(() => {
            ElMessage.info('已取消批量删除');
        });
};

// 批量启用处理函数
const handleBatchEnable = () => {
    if (selectedRows.value.length === 0) return;


    selectedRows.value.forEach(async(row) => {
        await updataUserState(row.username!, "1");
        row.status = "1";
    });

    ElMessage({
        type: 'success',
        message: `已批量启用 ${selectedRows.value.length} 条数据`,
    });

    // 如果需要，可以调用 API 更新状态
};

// 批量禁用处理函数
const handleBatchDisable = () => {
    if (selectedRows.value.length === 0) return;

    selectedRows.value.forEach(async(row) => {
        await updataUserState(row.username!, "0");
        row.status = "0";
    });

    ElMessage({
        type: 'success',
        message: `已批量禁用 ${selectedRows.value.length} 条数据`,
    });


};
//------------对话框----------------
const dialogVisible = ref(false)
// 在编辑的时候不可以选择租户dialogType:false，新增的时候可以选择租户 dialogType:true
const dialogType = ref(true)
const emit = defineEmits(['dialogUpdated']);
const onOpen = () => {
    emit('dialogUpdated', dialogVisible.value)
}
const onClose = () => {
    emit('dialogUpdated', dialogVisible.value)
}
const dialogTitle = ref('')
const handleClose = (done: () => void) => {
    dialogVisible.value = false
    // 重置验证规则，避免触发验证 需要用setTimeout包裹
    setTimeout(() => {
        dialogForm.value?.clearValidate()
    }, 100)
    done()
}
const segmentValue = ref('basic')

const menuoOptions = [
    {
        label: '基础信息',
        value: 'basic',
    },
    {
        label: '租户信息',
        value: 'tenant',
    }
]
//
const dialogForm = ref<FormInstance>()
const userForm = ref<UserDTO>({})
const rules = reactive<FormRules<UserDTO>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
    ],
    tenantId: [
        { required: true, message: '请选择租户', trigger: 'blur' },
    ],
    phone:[
        { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    email:[
        { required: true, message: '请输入邮箱', trigger: 'blur' },
    ],
});

// 编辑行的处理函数
const handleEdit = async (index:number,row: User) => {
    // 编辑逻辑
    dialogTitle.value = '编辑用户'
    dialogType.value = false
    dialogVisible.value = true

    userForm.value = row
    const tenant = await findById(row.tenantId || "");
    if (tenant) {
        userForm.value.tenantName = tenant.tenantName;
        console.log('tenant', tenant)
    }
   
};
const update = async () => {
    // 更新逻辑
    try {
        const valid = await dialogForm.value?.validate();
        if (valid) {
            if (dialogType.value === false) {
                // 更新逻辑
                await updateUser(userForm.value);
                ElMessage.success('更新成功');
            } else {
                // 新增逻辑
                // 验证租户是否选择
                if(!userForm.value.tenantId) {
                    ElMessage.error('请选择租户');
                    return;
                }
                await addUser(userForm.value);
                await getUserData();
                ElMessage.success('新增成功');
            }
           
        } else {
            // 验证失败的情况下，显示错误信息
            ElMessage.error('请检查输入项');
        }
    } catch (error) {
        // 捕获验证失败时的错误
        ElMessage.error('验证失败，请检查输入项');
       
    }
}

// 删除行的处理函数
const handleRowDelete = (index: number, row: User) => {

    ElMessageBox.confirm(`确定删除 ${row.username} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async() => {
            tableData.value.splice(index, 1);
            await deleteUser(row)
            ElMessage.success('删除成功');
            await getUserData();
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
};

const globalVar = globalVariables;
const ifTenantToUser = () => {  
    if (globalVar.tenantToUser) {
        searchData.value.tenantIdList.push(globalVar.tenantId);
        search();
    }
    globalVar.tenantToUser = false;
    globalVar.tenantId = ''
    setGlobalVar(false, '' );
};
onMounted(() => {  
    ifTenantToUser(); // 调用方法  
}); 

</script>
<style lang="scss" scoped>
@use "sass:color";
$primary-color: #6067eb;
$info-color: #dadcf6;
$button-border-radius: 4px;
$button-padding: 0.5rem 1rem;
$button-font-size: 16px;
$color-hover: color.adjust($primary-color, $lightness: -10%); // 悬浮时的颜色
$color-disabled: color.adjust($primary-color, $lightness: 15%); // 禁用时的颜色
$info-color-hover: color.adjust($info-color, $lightness: -25%); // 悬浮时的颜色

/* 定义一个 mixin 用于公共按钮样式 */
@mixin action-button-style {
    border-radius: $button-border-radius;
    padding: $button-padding;
    font-size: $button-font-size;
    cursor: pointer;
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;

    /* 覆盖 Element Plus 的 primary 按钮样式 */
    &.el-button--primary {
        background-color: $primary-color;
        border-color: $primary-color;
        color: #fff;

        &:hover,
        &:focus {
            background-color: $color-hover;
            border-color: $color-hover;
            color: #fff;
        }

        &.is-disabled {
            background-color: $color-disabled;
            border-color: $color-disabled;
            color: #fff;
            cursor: not-allowed;
            opacity: 1; // 确保颜色不被 Element Plus 默认的透明度覆盖
        }
    }

    &.el-button--info {
        background-color: $info-color;
        border-color: $info-color;
        color: #fff;

        &:hover,
        &:focus {
            background-color: $info-color-hover;
            border-color: $info-color-hover;
            color: #fff;
        }

        &.is-disabled {
            background-color: $color-disabled;
            border-color: $color-disabled;
            color: #fff;
            cursor: not-allowed;
            opacity: 1; // 确保颜色不被 Element Plus 默认的透明度覆盖
        }
    }

    /* 禁用状态下的样式（针对所有类型的按钮） */
    &:disabled,
    &.is-disabled {
        background-color: $color-disabled;
        border-color: $color-disabled;
        color: #fff;
        cursor: not-allowed;
        opacity: 1; // 覆盖 Element Plus 默认的透明度
    }


}

.action-button {
    @include action-button-style;
}

/* 按钮组样式 */
.button-group {
    display: flex;
    gap: 1rem;
    margin-bottom: 10px;
}

.table-button {
    color: #7e63cd;
    font-size: 14px;
    /* 设置你想要的字体大小 */
    font-weight: bold;
    /* 设置字体加粗 */
}


.search-card {
    border-radius: 10px;

    .block {
        padding: 0px 0;
        text-align: center;
        border-right: solid 1px var(--el-border-color);
        flex: 1;
    }

    .block:last-child {
        border-right: none;
    }

}


.pagination-container {
    display: flex;
    margin-top: 25px;
    justify-content: right;
    width: 100%;
    z-index: 1000;
}

.el-segmented {
    --el-segmented-item-selected-color: var(--el-text-color-primary);
    --el-segmented-item-selected-bg-color: #868cf4;
    --el-border-radius-base: 8px;
    --el-text-color-primary: #fff;
    --el-segmented-item-hover-bg-color: #b2b5f0;
    display: flex;
    justify-content: flex-start;
    /* 左对齐 */
    width: 300px;
    margin-bottom: 20px;
}
</style>